package com.youchuang.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import com.youchuang.bean.Category;

public class CategoryUtil {

	/**
	 * 获取同一个父id的list
	 * 
	 * @param list
	 * @param id
	 * @return
	 */
	public static List<Category> neatenByParentId(List<Category> categories, String partentId) {
		if (CollectionUtils.isEmpty(categories))
			return null;
		List<Category> subCats = null;
		List<Category> list = new ArrayList<>(Arrays.asList(new Category[categories.size()]));
		Collections.copy(list, categories);
		for (Category category : list) {
			if (category.getParentId().equals(partentId)) {
				if (subCats == null) {
					subCats = new ArrayList<>();
				}
				subCats.add(category);
			}
		}
		return subCats;
	}

	/**
	 * 分类整理
	 * 
	 * @param categories
	 * @return
	 */
	public static List<Category> neatenCategory(List<Category> categories, List<Category> allCategories) {
		if (CollectionUtils.isEmpty(categories))
			return null;
		List<Category> list = new ArrayList<>(Arrays.asList(new Category[categories.size()]));
		Collections.copy(list, categories);
		for (Category category : list) {
			List<Category> subCategories = CategoryUtil.neatenByParentId(allCategories, category.getId());
			category.setCategories(neatenCategory(subCategories, allCategories));
		}
		return list;
	}

	/**
	 * 获取对应所有子类集合
	 * 
	 * @param categoryId
	 * @param allCategories
	 * @return
	 */
	public static List<Category> getChilCategory(String categoryId, List<Category> allCategories) {
		List<Category> retuslt = new ArrayList<>();
		List<Category> list = new ArrayList<>(Arrays.asList(new Category[allCategories.size()]));
		Collections.copy(list, allCategories);
		for (Category category : list) {
			if (category.getParentId().equals(categoryId)) {
				retuslt.add(category);
				retuslt.addAll(getChilCategory(category.getId(), allCategories));
			}
		}
		return retuslt;
	}

}
